package com.yonyou.brigade.third_parties.hcholiday.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.model.IChannelConfig;
import com.yonyou.brigade.third_parties.hcholiday.constant.HcHolidayConstant;
import com.yonyou.brigade.third_parties.hcholiday.model.HcHolidayConfig;
import com.yonyou.brigade.third_parties.hcholiday.service.IHcHolidayPublicService;
import com.yonyou.brigade.util.operateutil.AESUtil4ECB;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 花城公共 服务实现类
 *
 * @author kangfw5
 * @date 2019-06-18
 */
@Service
public class HcHolidayPublicServiceImpl implements IHcHolidayPublicService {
    @Value("${hcholiday.url}")
    private String hcHolidayUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String getToken(IChannelConfig channelConfig) {
        HcHolidayConfig config = (HcHolidayConfig) channelConfig;
        String url = hcHolidayUrl + HcHolidayConstant.METHOD_POST_TOKEN.replace("{sender}", config.getSender());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        JSONObject resultJson = restTemplate.postForObject(url, entity, JSONObject.class);
        if ("success".equals(resultJson.getString("status"))) {
            try {
                return AESUtil4ECB.decrypt(resultJson.getString("data"), config.getSecretKey());
            } catch (Exception e) {
                throw new CustomException("花城token解密失败", e);
            }
        } else {
            throw new CustomException("花城token获取失败" + resultJson.getString("message"));
        }
    }
}
